﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using MetroFramework.Components;
using MetroFramework.Forms;

namespace IntelliTraceLauncher
{
    public partial class MainForm : MetroForm
    {
        internal readonly string[] PLAN_COLLECTION_PATH =
        {
            Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\IntelliTraceCPConfig.exe",
            Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + @"\IntelliTraceCPConfig\IntelliTraceCPConfig.exe",
            Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + @"\IntelliTraceCPConfig\IntelliTraceCPConfig\IntelliTraceCPConfig.exe",
            Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\IntelliTraceCPConfig\IntelliTraceCPConfig.exe",
            Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\IntelliTraceCPConfig\IntelliTraceCPConfig\IntelliTraceCPConfig.exe"
        };

        internal readonly string[] STANDALONE_COLLECTION_PATH =
        {
            Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\IntelliTraceSC.exe"
        };

        internal readonly string[] LOG_FILES_PATH =
        {
            Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\IntelliTrace"
        };

        private IntelliTraceApp[] m_appTile;
        private int m_appComboBoxIndex;

        #region Form Methods

        public MainForm()
        {
            InitializeComponent();

            LoadSettings();
            
            SetTheme();

            SetLaunchTiles();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveSettings();
        }

        #endregion Form Methods

        #region Theme Methods

        /// <summary>
        /// Sets the desired theme colour.
        /// </summary>
        private void SetTheme()
        {
            metroStyleManager.Style = ThemeColour.Style;
        }


        /// <summary>
        /// Populates the launch tiles, enabling
        /// them when the related app exists.
        /// </summary>
        private void SetLaunchTiles()
        {
            // iTrace Log Files
            if (Directory.Exists(metroTextBoxLogFiles.Text))
            {
                SetLogTile(true);
            }
            else
            {
                try
                {
                    Directory.CreateDirectory(metroTextBoxLogFiles.Text);
                    SetLogTile(true); // Only set true when dir is created.
                }
                catch
                {
                    SetLogTile(false); // Unable to create log dir.
                }
            }

            // IntelliTrace Plan Configurator
            if (File.Exists(metroTextBoxPlanConfigurator.Text))
            {
                metroTilePlanConfigurator.Enabled = true;
                metroTilePlanConfigurator.Style = ThemeColour.TilePlanConfigurator;
            }
            else
            {
                metroTilePlanConfigurator.Enabled = false;
                metroTilePlanConfigurator.Style = ThemeColour.TileDisabled;
            }

            // App Tiles
            SetAppTile(ref metroTileApp0, m_appTile[0].Name, m_appTile[0].Location);
            SetAppTile(ref metroTileApp1, m_appTile[1].Name, m_appTile[1].Location);
            SetAppTile(ref metroTileApp2, m_appTile[2].Name, m_appTile[2].Location);
            SetAppTile(ref metroTileApp3, m_appTile[3].Name, m_appTile[3].Location);
            SetAppTile(ref metroTileApp4, m_appTile[4].Name, m_appTile[4].Location);
            SetAppTile(ref metroTileApp5, m_appTile[5].Name, m_appTile[5].Location);
            SetAppTile(ref metroTileApp6, m_appTile[6].Name, m_appTile[6].Location);
            SetAppTile(ref metroTileApp7, m_appTile[7].Name, m_appTile[7].Location);
        }

        /// <summary>
        /// Enables or disables the log tiles.
        /// </summary>
        /// <param name="isEnabled">Value is true when tile should be enabled.</param>
        private void SetLogTile(bool isEnabled)
        {
            if (isEnabled)
            {
                metroTileLogFiles.Enabled = true;
                metroTileLogFiles.Style = ThemeColour.TilePlanConfigurator;

                metroTileLogFiles.TileCount = CalculateLogFiles(metroTextBoxLogFiles.Text);
            }
            else
            {
                metroTileLogFiles.Enabled = false;
                metroTileLogFiles.Style = ThemeColour.TileDisabled;
            }
        }

        /// <summary>
        /// Enables or disables an app tile and calculates its log file count.
        /// </summary>
        /// <param name="appTile">App tile to be set.</param>
        /// <param name="appName">Name of app to be displayed to user.</param>
        /// <param name="appPath">Filename including pathname of executable to be launched.</param>
        private void SetAppTile(ref MetroFramework.Controls.MetroTile appTile, string appName, string appPath)
        {
            if (File.Exists(appPath))
            {
                appTile.Enabled = true;
                appTile.Style = ThemeColour.TileEnabled;
                appTile.Text = appName;
            }
            else
            {
                appTile.Enabled = false;
                appTile.Style = ThemeColour.TileDisabled;
            }

            if (File.Exists(appPath) && Directory.Exists(metroTextBoxLogFiles.Text + @"\" + appName))
            {
                appTile.TileCount = CalculateLogFiles(metroTextBoxLogFiles.Text + @"\" + appName);
            }
        }

        #endregion Theme Methods

        #region Set IntelliTrace App Methods

        private IntelliTraceApp SetIntelliTraceApp(System.Collections.Specialized.StringCollection appArray, int position)
        {
            if (appArray != null && appArray.Count == 4)
            {
                bool showConsole = false;

                if(appArray[3].Equals(@"1") || appArray[3].Equals("true", StringComparison.OrdinalIgnoreCase))
                {
                    showConsole = true;
                }

                return new IntelliTraceApp()
                {
                    Name = appArray[0],
                    Location = appArray[1],
                    CollectionPlan = appArray[2],
                    ShowConsole = showConsole
                };
            }
            else
            {
                return new IntelliTraceApp()
                {
                    Name = "APP №" + position.ToString(),
                    Location = String.Empty,
                    CollectionPlan = String.Empty,
                    ShowConsole = false
                };
            }
        }

        private System.Collections.Specialized.StringCollection SetIntelliTraceApp(IntelliTraceApp appStruct)
        {
            System.Collections.Specialized.StringCollection appArray = new System.Collections.Specialized.StringCollection();

            appArray.Add(appStruct.Name);
            appArray.Add(appStruct.Location);
            appArray.Add(appStruct.CollectionPlan);

            if (appStruct.ShowConsole)
            {
                appArray.Add(@"1");
            }
            else
            {
                appArray.Add(@"0");
            }

            return appArray;
        }

        #endregion Set IntelliTrace App Methods

        #region Load / Save Settings

        private void LoadSettings()
        {
            m_appTile = new IntelliTraceApp[8];

            m_appTile[0] = SetIntelliTraceApp(Properties.Settings.Default.App0, 1);
            m_appTile[1] = SetIntelliTraceApp(Properties.Settings.Default.App1, 2);
            m_appTile[2] = SetIntelliTraceApp(Properties.Settings.Default.App2, 3);
            m_appTile[3] = SetIntelliTraceApp(Properties.Settings.Default.App3, 4);
            m_appTile[4] = SetIntelliTraceApp(Properties.Settings.Default.App4, 5);
            m_appTile[5] = SetIntelliTraceApp(Properties.Settings.Default.App5, 6);
            m_appTile[6] = SetIntelliTraceApp(Properties.Settings.Default.App6, 7);
            m_appTile[7] = SetIntelliTraceApp(Properties.Settings.Default.App7, 8);

            SetAppDetailsComboBox(m_appComboBoxIndex);

            /* First set the App Details Combo Box.
             * Only then add the event handler.*/
            m_appComboBoxIndex = 0;
            metroComboBoxAppDetails.SelectedIndex = 0;
            LoadAppDetails(metroComboBoxAppDetails.SelectedIndex);

            this.metroComboBoxAppDetails.SelectedIndexChanged += new System.EventHandler(this.metroComboBoxApp_SelectedIndexChanged);

            if (!Properties.Settings.Default.StandaloneCollector.Equals(String.Empty))
            {
                metroTextBoxStandaloneCollector.Text = Properties.Settings.Default.StandaloneCollector;
            }
            else
            {
                bool isFound = false;

                foreach (string filePath in STANDALONE_COLLECTION_PATH)
                {
                    if (File.Exists(filePath))
                    {
                        metroTextBoxStandaloneCollector.Text = filePath;
                        isFound = true;

                        break;
                    }
                }

                if (!isFound)
                {
                    metroTextBoxStandaloneCollector.Text = String.Empty;
                }
            }

            if (!Properties.Settings.Default.PlanConfigurator.Equals(String.Empty))
            {
                metroTextBoxPlanConfigurator.Text = Properties.Settings.Default.PlanConfigurator;
            }
            else
            {
                bool isFound = false;

                foreach (string filePath in PLAN_COLLECTION_PATH)
                {
                    if (File.Exists(filePath))
                    {
                        metroTextBoxPlanConfigurator.Text = filePath;
                        isFound = true;

                        break;
                    }
                }

                if (!isFound)
                {
                    metroTextBoxPlanConfigurator.Text = String.Empty;
                }
            }

            if (!Properties.Settings.Default.LogFiles.Equals(String.Empty))
            {
                metroTextBoxLogFiles.Text = Properties.Settings.Default.LogFiles;
            }
            else
            {
                Directory.CreateDirectory(LOG_FILES_PATH[0]);
                metroTextBoxLogFiles.Text = LOG_FILES_PATH[0];
            }
        }

        private void SaveSettings()
        {
            Properties.Settings.Default.App0 = SetIntelliTraceApp(m_appTile[0]);
            Properties.Settings.Default.App1 = SetIntelliTraceApp(m_appTile[1]);
            Properties.Settings.Default.App2 = SetIntelliTraceApp(m_appTile[2]);
            Properties.Settings.Default.App3 = SetIntelliTraceApp(m_appTile[3]);
            Properties.Settings.Default.App4 = SetIntelliTraceApp(m_appTile[4]);
            Properties.Settings.Default.App5 = SetIntelliTraceApp(m_appTile[5]);
            Properties.Settings.Default.App6 = SetIntelliTraceApp(m_appTile[6]);
            Properties.Settings.Default.App7 = SetIntelliTraceApp(m_appTile[7]);

            Properties.Settings.Default.StandaloneCollector = metroTextBoxStandaloneCollector.Text;
            Properties.Settings.Default.PlanConfigurator = metroTextBoxPlanConfigurator.Text;
            Properties.Settings.Default.LogFiles = metroTextBoxLogFiles.Text;

            Properties.Settings.Default.Save();
        }

        private void SaveAppDetails(int index)
        {
            if (index > -1 && index < m_appTile.Length)
            {
                m_appTile[index].Name = metroTextBoxAppName.Text;
                m_appTile[index].Location = metroTextBoxAppLocation.Text;
                m_appTile[index].CollectionPlan = metroTextBoxCollectionPlan.Text;
                m_appTile[index].ShowConsole = metroToggleShowConsole.Checked;
            }
        }

        private void LoadAppDetails(int index)
        {
            if (index > -1 && index < m_appTile.Length)
            {
                metroTextBoxAppName.Text = m_appTile[index].Name;
                metroTextBoxAppLocation.Text = m_appTile[index].Location;
                metroTextBoxCollectionPlan.Text = m_appTile[index].CollectionPlan;
                metroToggleShowConsole.Checked = m_appTile[index].ShowConsole;
            }
        }

        #endregion Load / Save Settings

        #region App Details Combo Box

        private void metroComboBoxApp_SelectedIndexChanged(object sender, EventArgs e)
        {
            SaveAppDetails(m_appComboBoxIndex);
            LoadAppDetails(metroComboBoxAppDetails.SelectedIndex);
            m_appComboBoxIndex = metroComboBoxAppDetails.SelectedIndex;
        }

        private void SetAppDetailsComboBox(int index)
        {
            metroComboBoxAppDetails.Items.Clear();

            foreach (IntelliTraceApp app in m_appTile)
            {
                metroComboBoxAppDetails.Items.Add(app.Name);
            }

            if (index > -1 && index < m_appTile.Length)
            {
                metroComboBoxAppDetails.SelectedIndex = index;
            }
            else
            {
                metroComboBoxAppDetails.SelectedIndex = 0;
            }

            m_appComboBoxIndex = metroComboBoxAppDetails.SelectedIndex;
        }

        #endregion App Details Combo Box

        #region Launch Tile Click Events

        private void metroTileLogFiles_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(metroTextBoxLogFiles.Text))
            {
                Process.Start(metroTextBoxLogFiles.Text);
            }
        }

        private void metroTilePlanConfigurator_Click(object sender, EventArgs e)
        {
            if (File.Exists(metroTextBoxPlanConfigurator.Text))
            {
                Process.Start(metroTextBoxPlanConfigurator.Text);
            }
        }

        private void metroTileApp0_Click(object sender, EventArgs e)
        {
            Thread tileThread = new Thread(new ParameterizedThreadStart(LaunchTileApp));
            tileThread.Start(0);
        }

        private void metroTileApp1_Click(object sender, EventArgs e)
        {
            Thread tileThread = new Thread(new ParameterizedThreadStart(LaunchTileApp));
            tileThread.Start(1);
        }

        private void metroTileApp2_Click(object sender, EventArgs e)
        {
            Thread tileThread = new Thread(new ParameterizedThreadStart(LaunchTileApp));
            tileThread.Start(2);
        }

        private void metroTileApp3_Click(object sender, EventArgs e)
        {
            Thread tileThread = new Thread(new ParameterizedThreadStart(LaunchTileApp));
            tileThread.Start(3);
        }

        private void metroTileApp4_Click(object sender, EventArgs e)
        {
            Thread tileThread = new Thread(new ParameterizedThreadStart(LaunchTileApp));
            tileThread.Start(4);
        }

        private void metroTileApp5_Click(object sender, EventArgs e)
        {
            Thread tileThread = new Thread(new ParameterizedThreadStart(LaunchTileApp));
            tileThread.Start(5);
        }

        private void metroTileApp6_Click(object sender, EventArgs e)
        {
            Thread tileThread = new Thread(new ParameterizedThreadStart(LaunchTileApp));
            tileThread.Start(6);
        }

        private void metroTileApp7_Click(object sender, EventArgs e)
        {
            Thread tileThread = new Thread(new ParameterizedThreadStart(LaunchTileApp));
            tileThread.Start(7);
        }

        #endregion Launch Tile Click Events

        #region App Details Tab

        private void metroTextBoxAppName_Leave(object sender, EventArgs e)
        {
            m_appComboBoxIndex = metroComboBoxAppDetails.SelectedIndex;
            SaveAppDetails(metroComboBoxAppDetails.SelectedIndex);
            SetAppDetailsComboBox(m_appComboBoxIndex);

            SetLaunchTiles(); // Refreshes the tiles
        }

        private void metroToggleShowConsole_CheckedChanged(object sender, EventArgs e)
        {
            m_appTile[metroComboBoxAppDetails.SelectedIndex].ShowConsole = metroToggleShowConsole.Checked;

            SaveAppDetails(metroComboBoxAppDetails.SelectedIndex);
        }

        private void metroButtonAppLocation_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = @"Executables|*.exe|All files|*.*";

            if (File.Exists(metroTextBoxAppLocation.Text))
            {
                FileInfo fileInfo = new FileInfo(metroTextBoxAppLocation.Text);
                openFileDialog.InitialDirectory = fileInfo.Directory.FullName;
            }

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                metroTextBoxAppLocation.Text = openFileDialog.FileName;
                m_appTile[metroComboBoxAppDetails.SelectedIndex].Name = openFileDialog.FileName;

                SaveAppDetails(metroComboBoxAppDetails.SelectedIndex);

                SetLaunchTiles(); // Refreshes the tiles
            }
        }

        private void metroTextBoxAppLocation_Leave(object sender, EventArgs e)
        {
            SaveAppDetails(metroComboBoxAppDetails.SelectedIndex);

            SetLaunchTiles(); // Refreshes the tiles
        }

        private void metroButtonCollectionPlan_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = @"XML files|*.xml|All files|*.*";

            if (File.Exists(metroTextBoxAppLocation.Text))
            {
                FileInfo fileInfo = new FileInfo(metroTextBoxAppLocation.Text);
                openFileDialog.InitialDirectory = fileInfo.Directory.FullName;
            }

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                metroTextBoxCollectionPlan.Text = openFileDialog.FileName;
                m_appTile[metroComboBoxAppDetails.SelectedIndex].CollectionPlan = openFileDialog.FileName;

                SaveAppDetails(metroComboBoxAppDetails.SelectedIndex);

                SetLaunchTiles(); // Refreshes the tiles
            }
        }

        private void metroTextBoxCollectionPlan_Leave(object sender, EventArgs e)
        {
            SaveAppDetails(metroComboBoxAppDetails.SelectedIndex);

            SetLaunchTiles(); // Refreshes the tiles
        }

        #endregion App Details Tab

        #region Settings Tab

        private void metroButtonStandaloneCollector_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = @"|IntelliTraceSC.exe|Executables|*.exe|All files|*.*";

            if (File.Exists(metroTextBoxStandaloneCollector.Text))
            {
                FileInfo fileInfo = new FileInfo(metroTextBoxStandaloneCollector.Text);
                openFileDialog.InitialDirectory = fileInfo.Directory.FullName;
            }

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                metroTextBoxStandaloneCollector.Text = openFileDialog.FileName;
            }
        }

        private void metroButtonPlanConfigurator_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = @"|IntelliTraceCPConfig.exe|Executables|*.exe|All files|*.*";

            if (File.Exists(metroTextBoxPlanConfigurator.Text))
            {
                FileInfo fileInfo = new FileInfo(metroTextBoxPlanConfigurator.Text);
                openFileDialog.InitialDirectory = fileInfo.Directory.FullName;
            }

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                metroTextBoxPlanConfigurator.Text = openFileDialog.FileName;

                SetLaunchTiles(); // Refreshes the tiles
            }
        }

        private void metroButtonLogFiles_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog openFolderDialogue = new FolderBrowserDialog();

            if (metroTextBoxLogFiles.Text.Equals(String.Empty) || !Directory.Exists(metroTextBoxLogFiles.Text))
            {
                openFolderDialogue.SelectedPath = LOG_FILES_PATH[0];
            }
            else
            {
                if(Directory.Exists(metroTextBoxLogFiles.Text))
                {
                    openFolderDialogue.SelectedPath = metroTextBoxLogFiles.Text;
                }
                else
                {
                    try
                    {
                        Directory.CreateDirectory(metroTextBoxLogFiles.Text);
                        openFolderDialogue.SelectedPath = metroTextBoxLogFiles.Text;
                    }
                    catch
                    {
                        Directory.CreateDirectory(LOG_FILES_PATH[0]);
                        openFolderDialogue.SelectedPath = LOG_FILES_PATH[0];
                    }
                }
            }

            if (openFolderDialogue.ShowDialog() == DialogResult.OK)
            {
                metroTextBoxLogFiles.Text = openFolderDialogue.SelectedPath;

                SetLaunchTiles(); // Refreshes the tiles
            }

            openFolderDialogue.Dispose();
        }
        
        private void metroTextBoxPlanConfigurator_Leave(object sender, EventArgs e)
        {
            SetLaunchTiles(); // Refreshes the tiles
        }

        private void metroTextBoxLogFiles_Leave(object sender, EventArgs e)
        {
            SetLaunchTiles(); // Refreshes the tiles
        }

        #endregion Settings Tab

        #region Create Process Functions

        /// <summary>
        /// Invokes a new process based on IntelliTraceSC and a given Tile App.
        /// </summary>
        /// <param name="indexTile">App tile index.</param>
        /// <returns>Value is true when process is started, otherwise false.</returns>
        private void LaunchTileApp(object tileIndex)
        {
            int index = (int) tileIndex;

            if (index <= -1 || index >= m_appTile.Length)
            {
                return; // no Tile App args to use
            }

            if(!File.Exists(metroTextBoxStandaloneCollector.Text) ||
                !File.Exists(m_appTile[index].Location) ||
                !File.Exists(m_appTile[index].CollectionPlan))
            {
                return; // no process to start
            }

            // E.g. %UserProfile%\MyDocuments\IntelliTrace
            if (!Directory.Exists(metroTextBoxLogFiles.Text))
            {
                Directory.CreateDirectory(metroTextBoxLogFiles.Text);
            }

            // E.g. %UserProfile%\MyDocuments\IntelliTrace\MyAppName
            if (!Directory.Exists(metroTextBoxLogFiles.Text + @"\" + m_appTile[index].Name))
            {
                Directory.CreateDirectory(metroTextBoxLogFiles.Text + @"\" + m_appTile[index].Name);
            }

            bool isLaunched = false;

            Random rand = new Random();
            string logTime = String.Format("{0:d/M/yyyy_HH:mm}", DateTime.Now) + @"-" + rand.Next(0, 999);
            string logFile = metroTextBoxLogFiles.Text + @"\" +
                             m_appTile[index].Name + @"\" +
                             m_appTile[index].Name + @"_" +
                             logTime.Replace(@":", @"").Replace(@"/", @"-") + @".iTrace";

            // IntelliTraceSC.exe launch /cp:"collection_plan.xml" /f:"%UserProfile\Desktop\MyAppName.iTrace" %ProgramFiles%\MyAppName\MyAppName.exe"
            string args = "launch /cp:\"" + m_appTile[index].CollectionPlan + "\" /f:\"" + logFile + "\" \"" + m_appTile[index].Location + "\"";

            ProcessStartInfo startInfo = new ProcessStartInfo();
            
            startInfo.FileName = metroTextBoxStandaloneCollector.Text;

            if (m_appTile[index].ShowConsole)
            {
                startInfo.CreateNoWindow = false;
                startInfo.UseShellExecute = false;
                startInfo.WindowStyle = ProcessWindowStyle.Normal;

                startInfo.RedirectStandardOutput = false;
                startInfo.RedirectStandardError = false;
            }
            else
            {
                startInfo.CreateNoWindow = true;
                startInfo.UseShellExecute = false;
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;

                startInfo.RedirectStandardOutput = true;
                startInfo.RedirectStandardError = true;
            }

            startInfo.Arguments = args;

            try
            {
                using (Process tileApp = new Process())
                {
                    tileApp.StartInfo = startInfo;

                    tileApp.EnableRaisingEvents = true;
                    //tileApp.SynchronizingObject = this;

                    if (!m_appTile[index].ShowConsole)
                    {
                        tileApp.OutputDataReceived += ProcessOutputDataReceived;
                        tileApp.ErrorDataReceived += ProcessOutputDataReceived;
                    }

                    tileApp.Exited += ProcessExited;

                    isLaunched = tileApp.Start();

                    if (!m_appTile[index].ShowConsole)
                    {
                        tileApp.BeginOutputReadLine();
                        tileApp.BeginErrorReadLine();
                    }

                    tileApp.WaitForExit();
                }
            }
            catch
            {
                // no code
            }
        }

        private void ProcessExited(object sender, EventArgs e)
        {
            SetLaunchTiles();
            ThreadHelper.AddText(this, richTextBoxConsole, "\n================================== Process Exited ==================================\n");
        }

        void ProcessOutputDataReceived(object sender, DataReceivedEventArgs eventArgs)
        {
            try
            {
                ThreadHelper.AddText(this, richTextBoxConsole, "\n" + eventArgs.Data);
                //richTextBoxConsole.Text += "\n" + eventArgs.Data;
            }
            catch
            {
                // Probably means the Standalone Collector process has closed.
                //Process tileApp = (Process)sender;
                //tileApp.ProcessOutputDataReceived -= ProcessOutputDataReceived;
                //tileApp.ErrorDataReceived -= ProcessOutputDataReceived;
            }
        }

        #endregion Create Process Functions

        /// <summary>
        /// Finds all of the iTrace files within the
        /// given directory and its sub directories.
        /// </summary>
        /// <param name="path">Location of iTrace log files.</param>
        /// <returns>Amount of iTrace log files within dir and sub dirs.</returns>
        private int CalculateLogFiles(string path)
        {
            var fileList = new DirectoryInfo(path).GetFiles("*.iTrace", SearchOption.AllDirectories);
            int count = ((FileInfo[])fileList).Length;
            
            return count;
        }

        private void metroButtonClearSettings_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(
                "This will reset all of your settings back to their default state.  Are you sure?", 
                "IntelliTrace Launcher - Clear Settings", 
                MessageBoxButtons.YesNo, 
                MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                Properties.Settings.Default.Reset();
                Environment.Exit(0);
            }
        }

        #region About Download Links

        private void linkLabelStandaloneCollector_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(@"http://www.microsoft.com/en-us/download/details.aspx?id=30665");
        }

        private void linkLabelPlanConfigurator_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(@"http://intellitracecpconfig.codeplex.com");
        }

        private void linkLabelLauncher_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(@"http://intellitracelauncher.codeplex.com");
        }

        #endregion About Download Links
    }
}